package advanced.sorm;

import advanced.sorm.bean.Configuration;

import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 根据配置信息, 维持连接对像的管理
 */


public class DBManager {
    private static Configuration conf;

    static {
        //静态块, 仅加载依次
        Properties pros = new Properties();
        try {
            //加载配置文件
            pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        conf = new Configuration();
        conf.setUrl(pros.getProperty("url"));
        conf.setDriver(pros.getProperty("driver"));
        conf.setUsername(pros.getProperty("user"));
        conf.setPassword(pros.getProperty("psw"));
        conf.setSrcPath(pros.getProperty("srcPath"));
        conf.setUsingDB(pros.getProperty("usingDB"));
        conf.setPoPackage(pros.getProperty("poPackage"));
    }

    public static Connection getConn() {
        try {
            Class.forName(conf.getDriver());
            return DriverManager.getConnection(conf.getUrl(), conf.getUsername(), conf.getPassword());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void close(Closeable... args) {
        for (Closeable arg : args) {
            if (arg != null) {
                try {
                    arg.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static Configuration getConf() {
        return conf;
    }

}
